﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using LiteQuery.Common;

namespace LiteQuery.Controls
{
    public partial class FuncPanel : UserControl
    {
        Entities.Config config;
        public Entities.Config Config
        {
            get { return config; }
            set { config = value; }
        }

        Entities.Func func;
        public Entities.Func PanelInfo
        {
            get { return func; }
            set { func = value; }
        }

        FuncPanelHelper.FuncPanel funcPanel;


        public FuncPanel()
        {
            InitializeComponent();
            funcPanel = new FuncPanelHelper.FuncPanel();
        }

        public FuncPanel(Entities.Func f, Entities.Config cfg)
        {
            InitializeComponent();
            this.PanelInfo = f;
            this.Config = cfg;
            this.plQuery.Height = f.Query.Heigth;
            funcPanel = new FuncPanelHelper.FuncPanel();
        }

        // 初始化面板
        private void FuncPanel_Load(object sender, EventArgs e)
        {
            plQuery.Controls.Add(new Controls.QueryPanel(func.Query) { Dock= DockStyle.Fill});
            plContent.Controls.Add(new Controls.DataPanel(func.DataSql) { Dock = DockStyle.Fill });
        }

        public void Query()
        {
            var quer = (plQuery.Controls[0] as QueryPanel);
            var data = (plContent.Controls[0] as DataPanel);
            var sql = data.DataSql.Sql + quer.Query.GetWhereSQL(data.DataSql.HasWhere);

            var ret = funcPanel.Query(this.Config.DataSource, sql);
            if (ret == null)
                return;
            // 绑定数据
            (plContent.Controls[0] as DataPanel).DataSource = ret.Tables[0];
        }

        public void Export(string path)
        {
            var data = (plContent.Controls[0] as DataPanel);
            if (funcPanel.ExportToExcel(data.DataSource, path).Item1)
                Common.WinForm.ShowInfo("导出成功");
            else
                Common.WinForm.ShowEror("导出失败");
        }
        // TODO: 导入向导中, 表名的命名规则
        // TODO: Excel的格式说明
        // TODO: 多表关联的处理
        // TODO: 配置文件的动态加载
        // TODO: 配置文件配置向导

        // TODO: 关系追溯
        // TODO: 关系图谱
    }
}
